using System;
using System.Collections.Specialized;
using System.Web.Security;
using Castle.MonoRail.Framework;
using Saffron.Framework.Users;

namespace Saffron.Filters
{
    public class AuthenticationFilter : IFilter
    {
        #region IFilter Members

        public bool Perform(ExecuteEnum exec, IRailsEngineContext context, Controller controller)
        {
            // Read previous authenticated principal from session 
            // (could be from cookie although with more work)

            UserAccount user = (UserAccount)context.Session["user"];

            // Sets the principal as the current user
            context.CurrentUser = user;

            // Checks if it is OK
            if (context.CurrentUser == null ||
                !context.CurrentUser.Identity.IsAuthenticated)
            {
                // Not authenticated, redirect to login
                NameValueCollection parameters = new NameValueCollection();
                parameters.Add("ReturnUrl", context.Url);
                controller.Redirect("login", "index", parameters);

                // Prevent request from continue
                return false;
            }

            controller.PropertyBag["user"] = user;

            // Everything is ok
            return true;
        }

        #endregion
    }
}
